package com.woniuxy.intellihome.controller.ucenter;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.intellihome.entity.*;
import com.woniuxy.intellihome.service.OrderService;
import com.woniuxy.intellihome.service.OrderitemService;
import com.woniuxy.intellihome.service.ReviewService;
import com.woniuxy.intellihome.service.UserService;
import com.woniuxy.intellihome.utils.UtilsTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author pengZhihong
 * @since 2021-08-14
 * 1、完成后台订单筛选、查询、分页、删除、修改功能，实现基本功能的搭建
 */
@Slf4j
@Controller("/ucenter/order")
@RequestMapping("/ucenter/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderitemService orderitemService;
    @Autowired
    private ReviewService reviewService;

    /**
     * 根据user_id获取对应订单及明细，发送model于前端页面
     * @param session nds
     * @param model 查询到的order信息打包发送至前端
     * @return ucenter/order页面
     */
    @GetMapping("/list")
    public String list(HttpSession session ,Model model) {
        //获取当前登录用户

        //仅测试用
        User user = (User)session.getAttribute("user1");
        model.addAttribute("user",user);
        //设置变量统计orderitem数量与已完成订单数量orderOver
        int itemscount = 0;
        int orderOver = 0;
        //通过usrId获取订单与订单明细
        List<Order> orders = orderService.getByUserId(user.getId());
        for (Order order : orders) {
            List<Orderitem> orderitems = orderitemService.getWithSKUByOrderId(order.getId());
            itemscount += orderitems.size();
            order.setOrderitems(orderitems);
            if (order.getStatus().equals("6")) {
                orderOver++;
            }
        }
        model.addAttribute("orders", orders);
        model.addAttribute("itemscount", itemscount);
        model.addAttribute("orderOver", orderOver);
        model.addAttribute("orderDoing", orders.size() - orderOver);

        return "/ucenter/user_order";
    }

    /**
     * 1、根据前台数据变化修改订单(仅修改订单，订单明细未变动)
     * 2、对删除订单功能，实现订单status状态的修改，使order被动隐藏
     * @param order 前台返回order信息
     * @param result
     * @return JSON语句
     */
    @PostMapping("/update")
    @ResponseBody
    public ResponseEntity update(@RequestBody Order order, BindingResult result){
        //创建JSON返回语句对象
        ResponseEntity responseEntity = new ResponseEntity();
        //检查是否存在错误
        if(result.hasFieldErrors()){
            //不存在返回无效提示
            Map<String,String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e ->{
                msgs.put(e.getField(),e.getDefaultMessage());
            });
            responseEntity.setCode(ResponseState.INVALIDARGS);
            responseEntity.setMsg("无效参数");
            responseEntity.setData(msgs);
        }else{
            //获取当前时间为订单接收时间
            order.setAcceptTime(UtilsTools.getTimeNow());
            orderService.saveOrUpdate(order);
            //返回修改结果
            responseEntity.setCode(ResponseState.SUCCESS);
            responseEntity.setMsg("成功");
            responseEntity.setData(order);
            return responseEntity;
        }
        return responseEntity;
    }

    @PostMapping("/review")
    @ResponseBody
    public ResponseEntity modReview(@RequestBody Order order, BindingResult result,HttpSession session){
        //创建JSON返回语句对象
        ResponseEntity responseEntity = new ResponseEntity();
        //检查是否存在错误
        if(result.hasFieldErrors()){
            //不存在返回无效提示
            Map<String,String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e ->{
                msgs.put(e.getField(),e.getDefaultMessage());
            });
            responseEntity.setCode(ResponseState.INVALIDARGS);
            responseEntity.setMsg("无效参数");
            responseEntity.setData(msgs);
        }else{

            //获取orderitems
            List<Orderitem> orderitems = order.getOrderitems();
            orderitems.forEach(o -> {
                //赋商品skuid
                Review review = o.getReview();
                review.setSkuId(o.getSkuId());
                //添加评论
                Boolean check = add(o.getReview(),session);
                System.out.println(check);
            });
            order.setStatus("6");
            orderService.saveOrUpdate(order);
        }
        responseEntity.setCode(ResponseState.SUCCESS);
        responseEntity.setMsg("成功");
        responseEntity.setData(orderService.getById(order.getId()));
        return responseEntity;
    }


    //通过用户ID和SKUid增加评论
    public boolean add(Review review,HttpSession session) {
        System.out.println(review);
        User user = (User) session.getAttribute("user1");
        Review r = new Review();
        if (review.getContent() != null) {
            r.setContent(review.getContent());
        } else {
            return false;
        }
        if (review.getType() != null) {
            r.setType(review.getType());
        } else {
            return false;
        }
        try {
            r.setTime(UtilsTools.getTimeNow());
            r.setUserId(user.getId());
            r.setSkuId(review.getSkuId());

            System.out.println(r);
            reviewService.addReview(r.getContent(), r.getType(), r.getTime(), r.getUserId(), r.getSkuId());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

